import react from '@vitejs/plugin-react'
import vitePluginImp from 'vite-plugin-imp'
import { fileURLToPath, URL } from 'url';
import { VitePWA } from 'vite-plugin-pwa';
import legacy from '@vitejs/plugin-legacy';
const fs = require('fs');
const path = require('path');
const { encode: base64Encode } = require('base64-arraybuffer');

// https://vitejs.dev/config/
export default ({ mode }) => {

    const isDev = (mode === "development");
    const isProd = (mode === "production");

    const myDate = new Date();
    const nowDate = `${myDate.getFullYear()}-${myDate.getMonth() + 1}-${myDate.getDate()} ${myDate.getHours()}:${myDate.getMinutes()}:${myDate.getSeconds()}`;

    return ({
        base: "./",
        // 全局替换
        define: {
            "process.env.BUILD_TIME": `'${nowDate}'`,
        },

        build: {
            targets: ["es2015"],
            assetsInlineLimit: 1024 * 10,
            minify: 'terser',
            terserOptions: {
                compress: {
                    drop_console: false,
                    drop_debugger: true,
                }
            },
            chunkSizeWarningLimit: 1024 * 100,
            rollupOptions: {
                input: {
                    "index": fileURLToPath(new URL('./index.html', import.meta.url)),
                    "3d_box": fileURLToPath(new URL('./3d_box.html', import.meta.url)),
                    "3d_carousel": fileURLToPath(new URL('./3d_carousel.html', import.meta.url)),
                    "3d_text_ball": fileURLToPath(new URL('./3d_text_ball.html', import.meta.url)),
                    "3d_hrl": fileURLToPath(new URL('./3d_hrl.html', import.meta.url)),
                }
            }
        },
        plugins: [
            react(),
            (() => {
                return {
                    name: 'base64-plugin',
                    async transform(code, id) {
                        if (/\.(jpg|jpeg|png)/.test(id)) {
                            const fileBuffer = await fs.readFileSync(id);
                            const fileExt = path.extname(id).slice(1);
                            const encoded = base64Encode(fileBuffer);
                            const dataUrl = `data:image/${fileExt};base64,${encoded}`;
                            code = `export default "${dataUrl}"`;
                            return { code };
                        }
                    }
                }
            })(),
            vitePluginImp({
                optimize: true,
                libList: [
                    {
                        libName: 'antd',
                        libDirectory: 'es',
                        style: (name) => `antd/es/${name}/style`
                    },
                    {
                        libName: 'antd-mobile',
                        style: () => false,
                        libDirectory: 'es/components',
                        replaceOldImport: true
                    }
                ]
            }),
            legacy({
                targets: ['defaults', 'not IE 11']
            })
            // isProd && VitePWA({
            //     scope: "/effect_text/",
            //     mode,
            //     minify: false,
            //     registerType: 'autoUpdate',
            //     workbox: {
            //         // 自定义前端缓存的文件
            //         globPatterns: ["**\/*.{js,css,html,png,jpg,jpeg,gif,ico,svg,wasm,glb,gltf,fbx,pdf,mp3,mp4,ttf}"],
            //         maximumFileSizeToCacheInBytes: 1024 * 1024 * 50, // 最大50MB
            //     }
            // })
        ],
        resolve: {
            alias: {
                "@hashHistory": fileURLToPath(new URL('./src/hashHistory', import.meta.url)),
                "@utils": fileURLToPath(new URL('./src/utils/utils.ts', import.meta.url)),
                "@views": fileURLToPath(new URL('./src/views', import.meta.url)),
                "@globalStore": fileURLToPath(new URL('./src/globalStore.ts', import.meta.url)),
                "@components": fileURLToPath(new URL('./src/components', import.meta.url)),
                "@service": fileURLToPath(new URL('./src/service', import.meta.url)),
            }
        },
        css: {
            preprocessorOptions: {
                less: {
                    javascriptEnabled: true,// 支持内联 javascript
                },
            }
        },
        server: {
            proxy: {
                '/api': {
                    target: 'http://jsonplaceholder.typicode.com',
                    changeOrigin: true,
                    rewrite: (path) => path.replace(/^\/api/, '')
                },
            }
        }
    })

}
